﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NerdDinner.Models;
using System.Net;
using System.IO;
using System.Xml.Linq;

namespace NerdDinner.Controllers
{
    public struct TwitterData
    {
        public String Content;
        public String Updated;
        public String AuthorName;
        public String AuthorUri;
        public String Link;
    }
        
    
    public class BookController : Controller
    {
        public ActionResult TwitterResults(string BookName)
        {
            TwitterResults twitterResults   = new TwitterResults();
            twitterResults.BookName         = BookName;
            
            if (!String.IsNullOrEmpty(BookName))
            {
                String requestUrl       = @"http://search.twitter.com/search.atom?lang=en&q=" + Url.Encode(BookName);
                HttpWebRequest request  = (HttpWebRequest)WebRequest.Create(requestUrl);

                if (request != null)
                {
                    HttpWebResponse response    = (HttpWebResponse)request.GetResponse();
                    StreamReader reader         = new StreamReader(response.GetResponseStream());

                    String rawResults   = reader.ReadToEnd();
                    XDocument results   = XDocument.Parse(rawResults);
                    XNamespace xmlns    = @"http://www.w3.org/2005/Atom";

                    twitterResults.Result = (from entry in results.Descendants(xmlns + "entry")

                                                select new TwitterData
                                                {
                                                    Content     = entry.Element(xmlns + "content").Value,
                                                    Updated     = entry.Element(xmlns + "updated").Value,
                                                    AuthorName  = entry.Element(xmlns + "author").Element(xmlns + "name").Value,
                                                    AuthorUri   = entry.Element(xmlns + "author").Element(xmlns + "uri").Value,
                                                    Link        = ( from o in entry.Descendants(xmlns + "link")
                                                                    where o.Attribute("rel").Value == "image"
                                                                    select new { Val = o.Attribute("href").Value }).First().Val
                                                }).ToList();
                }
            }
                
            return View(twitterResults);
        }
    }
}
